import pygame

SCREEN_SIZE = (480, 700)


class GameSprite(pygame.sprite.Sprite):
    def __init__(self, file_name, speed=1):
        super().__init__()
        self.image = pygame.image.load(file_name)
        self.rect = self.image.get_rect()
        self.speed = speed

    def update(self):
        self.rect.y += 1

class BgSprite(GameSprite):
    def __init__(self, is_pre=False):
        super().__init__('./images/background.png')
        if is_pre:
            self.rect.y = -self.rect.height
    def update(self):
        super().update()
        if self.rect.y >= self.rect.height:
            self.rect.y = -self.rect.height



class Plane(GameSprite):
    def __init__(self, file_name, speed=1):
        super().__init__(file_name, speed)
        self.rect.centerx = SCREEN_SIZE[0]//2
        self.rect.bottom = SCREEN_SIZE[1]

    def update(self):
        pass

class Game:
    def __init__(self):
        self.is_loop = True

    def main(self):
        pygame.init()
        self.screen = pygame.display.set_mode(SCREEN_SIZE)
        pygame.display.set_caption("飞机大战")
        self.create_sprites()
        while self.is_loop:
            self.screen.fill([0,0,0])
            self.__event_handler()
            self.update_sprites()
            pygame.display.update()
        pygame.quit()

    def __event_handler(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.is_loop = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    self.hero.rect.x-=10
                    if self.hero.rect.x<0:
                        self.hero.rect.x = 0
                elif event.key == pygame.K_RIGHT:
                    self.hero.rect.x += 10
                    if self.hero.rect.x > SCREEN_SIZE[0]-self.hero.rect.w:
                        self.hero.rect.x = SCREEN_SIZE[0]-self.hero.rect.w

    def create_sprites(self):
        bg1 = BgSprite()
        bg2 = BgSprite(True)
        self.group_bg = pygame.sprite.Group(bg1, bg2)
        self.hero = Plane('./images/me1.png')
        self.group_hero = pygame.sprite.Group(self.hero)

    def update_sprites(self):
        self.group_bg.update()
        self.group_bg.draw(self.screen)
        # self.group_hero.update()
        self.group_hero.draw(self.screen)


g = Game()
g.main()
